import { Component, OnInit, OnDestroy } from "@angular/core";
import { TreeNode, TypeMapper } from "../one-map";
import { MapUiService } from "../map-ui.service";
import { OneMapService } from "../one-map.service";
import { takeUntil } from "rxjs/operators";
import { Subject, of } from "rxjs";
import { LatLonArray, OverlayService, OpenlayersService } from "unified-map";
import { DialogInfoComponent } from "../dialog-info/dialog-info.component";
import InfoConfig, { RegionInfo } from "../dialog-info/info.config";
import * as _ from 'lodash';

@Component({
  selector: "app-base-info",
  templateUrl: "./base-info.component.html",
  styleUrls: ["./base-info.component.scss"]
})
export class BaseInfoComponent implements OnInit, OnDestroy {
  private unsubscribe = new Subject<void>();
  init: boolean = true;
  treeNode: any[] = [];
  overlayData: any = {};
  panelItem: any = {
    mode: "base",
    layerName: "office"
  };
  typeMapper: any = TypeMapper;

  constructor(
    private mapUiService: MapUiService,
    private mapService: OneMapService,
    private overlayService: OverlayService,
    private olService: OpenlayersService
  ) { }

  ngOnInit(): void {
    this.treeNode = _.cloneDeep(TreeNode);
    this.mapUiService.modeChange.next("base");
    this.mapUiService.treeNodeChange.next({
      treeNode: this.treeNode,
      initMap: true
    });
    this.mapUiService.panelChange.next(this.panelItem);
    // this.mapUiService.entityClicked
    //   .pipe(takeUntil(this.unsubscribe))
    //   .subscribe(entity => {
    //     this.entityClicked(entity);
    //   });
    // this.mapUiService.entityHovered
    //   .pipe(takeUntil(this.unsubscribe))
    //   .subscribe(entity => {
    //     this.entityHovered(entity);
    //   });
    this.mapUiService.buildingSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(data => {
        // console.log(data);
        this.overlayData = {
          ...data,
          show: true
        };
        this.createOverlay(this.overlayData);
      });
    this.mapUiService.searchSelected
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(item => {
        this.onSearchSelect(item);
      });
    this.init = false;
  }

  ngOnDestroy(): void {
    this.overlayService.clear();
    this.unsubscribe.next();
    this.unsubscribe.complete();
  }

  entityClicked(entity) {
    console.log("----------entityClicked base-----------");
    if (!entity || !entity.layer || entity.layer == "boundary" || this.init) {
      this.mapUiService.twinkleOverlay.setPosition(null);
      this.mapUiService.showTwinkle = false;
      return;
    }
    const { properties = {}, position } = entity;
    const latLon = this.mapUiService.mapInstance.getPositionByEntity(
      entity.layer,
      entity.id
    );
    let layer = entity.layer;
    layer = layer.split("_").pop();

    if (latLon && latLon.length == 2) {
      const pointPosition = this.mapUiService.transformCoordinate(latLon);
      this.mapUiService.twinkleOverlay.setPosition(pointPosition);
      this.mapUiService.showTwinkle = true;
    } else {
      this.mapUiService.twinkleOverlay.setPosition(null);
      this.mapUiService.showTwinkle = false;
    }

    // 显示基本信息
    this.getBaseInfo2({
      ...properties,
      latLon,
      position,
      layer
    });
  }

  onSearchSelect(item) {
    console.log(item);
    item.layer = this.typeMapper[item.type];
    this.getBaseInfo2(item);
    let selectNode;
    this.treeNode.map(parent => {
      if (parent.children) {
        parent.children.map(node => {
          if (node.layerName && node.layerName.split('_').indexOf(item.layer) >= 0) {
            node.checked = true;
            selectNode = node;
          }
        });
      }
    });
    this.mapUiService.treeNodeChange.next({
      treeNode: this.treeNode,
      initMap: false
    });
    this.mapUiService.selectNode(this.treeNode, selectNode);
  }

  getBaseInfo2(item) {
    let queryObs;
    switch (item.layer) {
      case 'zuzhi@1':
      case 'zuzhi@2':
        queryObs = this.mapService.queryOffice({
          manageCode: item.code || item.buildCode
        });
        break;
      case 'bengzhan':
      case 'bengzhan2':
        queryObs = this.mapService.queryBengzhan({
          pumpCode: item.code || item.buildCode
        });
        break;
      // case 'paishuigou':
      //   queryObs = this.mapService.queryPaishuigou({
      //     drainageCode: item.buildCode
      //   });
      //   break;
      case 'qiaoliang':
        queryObs = this.mapService.queryBridge({
          bridgeCode: item.code || item.buildCode
        });
        break;
      case 'yiliuyan':
        queryObs = this.mapService.queryYiliuyan({
          code: item.code || item.buildCode
        });
        break;
      case 'ganqu-yjq':
        queryObs = this.mapService.queryCanal({
          canalName: item.name || item.buildName || item.canalName || item.Name
        });
        break;
      case 'handong':
        queryObs = this.mapService.queryHandong({
          culvertCode: item.code,
          culvertName: item.name,
          stationId: item.station_id,
          sectionId: item.section_id
        });
        break;
      case 'ducao':
        queryObs = this.mapService.queryDucao({
          flumeName: item.name || item.buildName
        });
        break;
      case 'jinshuizha':
      case 'tuishuizha':
      case 'jiezhizha':
        queryObs = this.mapService.queryGate({
          strobeCode: item.code || item.buildCode
        });
        break;
      case 'dieshui':
        queryObs = this.mapService.queryDieshui({
          dropCode: item.code || item.buildCode
        });
        break;
      case 'zhikaikou':
        queryObs = this.mapService.queryZhikaikou({
          watergateCode: item.name || item.buildName
        });
        break;
      case 'zhihongqu':
        queryObs = this.mapService.queryZhihongqu({
          detentionName: item.name || item.buildName
        });
        break;
      case 'shanhonggou':
        queryObs = this.mapService.queryShanhonggou({
          floodName: item.name || item.buildName
        });
        break;
      case 'gyysdw':
        queryObs = this.mapService.queryGyysdw({
          name: item.name || item.buildName
        });
        break;
      case 'hd': // 河道水文站
      case 'yz': // 堰闸水文站
      case 'hh': // 黄河断面
      case 'skswz': // 水库水文站
      case 'gqdm': // 干渠断面
      case 'shg': // 山洪沟断面
      case 'psg': // 排水沟断面
      case 'ylz': // 雨量站
      case 'cyylz': // 雨量站
      case 'sqz': // 墒情站
        queryObs = this.mapService.getSectionInfo(item.Stadia_Code || item.buildCode);
        break;
      case 'db': // 地表取水口
      case 'dx': // 地下取水口
      case 'gy': // 工业取水口
      case 'ny': // 农业取水口
      case 'sh': // 生活取水口
        queryObs = this.mapService.getIntakeInfo(item.wiust_cd || item.buildCode);
        break;
      case 'zlqsk':
        queryObs = this.mapService.getInfoZQSK(item.ID || item.buildCode);
        break;
      case 'qdlqsk':
        queryObs = this.mapService.getInfoQDQSK(item.ID || item.buildCode);
        break;
      case 'bzlqsk':
        queryObs = this.mapService.getInfoBZQSK(item.ID || item.buildCode);
        break;
      case 'sjlqsk':
        queryObs = this.mapService.getInfoSJQSK(item.ID || item.buildCode);
        break;
      case 'blqsk':
        queryObs = this.mapService.getInfoBQSK(item.ID || item.buildCode);
        break;
      case 'sdzlqsk':
        queryObs = this.mapService.getInfoSDZQSK(item.ID || item.buildCode);
        break;
      case 'qtlqsk':
        queryObs = this.mapService.getInfoQTQSK(item.ID || item.buildCode);
        break;
      default:
        queryObs = of({});
        break;
    }
    queryObs.subscribe(res => {
      console.log(res);
      if (res["list"] && res["list"].length) {
        this.panelItem = {
          mode: 'info',
          ...item,
          ...res["list"][0]
        };
      } else {
        this.panelItem = {
          mode: 'info',
          ...item,
          ...res
        };
      }
      this.mapUiService.panelChange.next(this.panelItem);
      // this.createOverlay(this.overlayData);
    });
  }

  createOverlay(item) {
    if (!item.layer) {
      item.layer = this.typeMapper[`${item.typeNum}`];
      if (item.typeNum == 9) {
        item.layer =
          item.watergateType == 1
            ? "jinshuizha"
            : item.watergateType == 2
              ? "tuishuizha"
              : "jiezhizha";
      }
    } else if (item.layer == "County") {
      const data = RegionInfo[item.Code.slice(0, 4)];
      item = { ...item, ...data };
    }
    const config = InfoConfig[item.layer];
    let location = item.latLon
      ? item.latLon
      : item.geom
        ? [item.geom.lng, item.geom.lat]
        : [];
    if (item.layer == "County") {
      location = this.mapUiService.mapInstance.getLocationByPosition(
        item.position
      );
    }
    if (config) {
      const h = this.mapUiService.mainCompEl.nativeElement.getBoundingClientRect()
        .height;
      const overlayHeight = config.height + 45;
      const overlayPTop = Math.abs(h - overlayHeight - 50) / 2 + overlayHeight;
      this.mapUiService.mapInstance
        .flyTo(location as LatLonArray, {
          zoom: this.mapUiService.currentZoom > 12 ? this.mapUiService.currentZoom : 12,
          duration: 500,
          padding: [overlayPTop, 0, 0, 0]
        })
        .then(() => {
          this.overlayService.createOverlay(
            DialogInfoComponent,
            {
              longitude: location[0],
              latitude: location[1],
              title: item[config.ttlName],
              showLeader: true,
              width: 418,
              height: overlayHeight,
              offset: { x: 0, y: -15 },
              singleton: true,
              destroyOnClose: true,
              opacity: 0.8,
              data: item
            },
            true
          );
        });
    }

    // this.mapUiService.flyToPoint(location);
  }
}
